package com.unknowpupil.design.sigleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Description: <br/>
 * <p>
 * （测试 反射和反序列化漏洞）
 * </p>
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/4/24 17:46
 * @Classname: Client
 * @Version: 1.0
 */
public class Client {

    public static void main(String[] args) throws Exception {
        HungrySingleton s1 = HungrySingleton.getInstance();
        HungrySingleton s2 = HungrySingleton.getInstance();
        System.out.println(s1);
        System.out.println(s2);
/**
        // java 1.8 已经由防止 反射获取私有单例了。
        //反射
        Class<LazySingleton> clazz = (Class<LazySingleton>) Class.forName("com.unknowpupil.design.sigleton.LazySingleton");
        //无参构造器
        Constructor<LazySingleton> constructor = clazz.getDeclaredAnnotation(null);
        //跳过权限检查。访问私有
        constructor.setAccessible(true);
        // 创建对象
        LazySingleton hungrySingleton1 = constructor.newInstance();
        LazySingleton hungrySingleton2 = constructor.newInstance();
        System.out.println(hungrySingleton1);
        System.out.println(hungrySingleton2);

*/
        /**
         * 序列化
         */
        FileOutputStream fos = new FileOutputStream("d:/a.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s1);
        oos.close();
        fos.close();

        /**
         * 反序列化
         */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/a.txt"));
        HungrySingleton o = (HungrySingleton)ois.readObject();
        System.out.println(o);

    }
}
